#include "../../mqServer/mq_message.hpp"
#include <gtest/gtest.h>

using namespace mq;
MessageManager::manager_ptr mmp;

class MessageTest : public testing::Environment
{
public:
    virtual void SetUp() override
    {
        cout << "所有单元测试前执行环境初始化" << endl;
        mmp = make_shared<MessageManager>("./data/message/");
        mmp->initQueueMessage("queue1");
    }
    virtual void TearDown() override
    {
        cout << "所有单元测试后执行环境清理" << endl;
        // mmp->clear();
        mmp->destroyQueueMessage("queue1");
    }
};

int n = 10000;
stack<m_ptr> st;
TEST(message_test, insert_test)
{
    for (int i = 0; i < n; i++) // 插入n条数据
    {
        BasicProperties properties;
        properties.set_id(UUIDHelper::uuid());
        properties.set_routing_key("abc*sja$sha---" + to_string(i));
        properties.set_delivery_mode(DeliveryMode::DURABLE);
        mmp->insert("queue1", &properties, "hello msg---" + to_string(i), true);
    }
    ASSERT_EQ(mmp->getable_count("queue1"), n);
    ASSERT_EQ(mmp->waitack_count("queue1"), 0);
    ASSERT_EQ(mmp->vaild_count("queue1"), n);
    ASSERT_EQ(mmp->total_count("queue1"), n); // 检测各项消息数量
}

TEST(message_test, get_front_test)
{
    for (int i = 1; i <= n; i++)
    {
        m_ptr msgp = mmp->front("queue1");
        ASSERT_NE(msgp, m_ptr());
        st.push(msgp);
        // cout << "get front msg:" << msgp->payload().properties().id() << endl;
        ASSERT_EQ(mmp->getable_count("queue1"), n - i);
        ASSERT_EQ(mmp->waitack_count("queue1"), i);
        ASSERT_EQ(mmp->vaild_count("queue1"), n);
        ASSERT_EQ(mmp->total_count("queue1"), n);
    }
    m_ptr msgp = mmp->front("queue1");
    ASSERT_EQ(msgp, m_ptr()); // 队列待推送链表无消息，再次获取为空
}

TEST(message_test, ack_test)
{
    ASSERT_EQ(st.size(), n);
    for (int i = 1; i <= n / 2 + 1; i++)
    {
        m_ptr msgp = st.top();
        st.pop();
        mmp->ack("queue1", msgp->payload().properties().id());
        ASSERT_EQ(mmp->getable_count("queue1"), 0);
        ASSERT_EQ(mmp->waitack_count("queue1"), n - i);
        ASSERT_EQ(mmp->vaild_count("queue1"), n - i);
    }
    cout << "getable_count:" << mmp->getable_count("queue1") << endl;
    cout << "waitack_count:" << mmp->waitack_count("queue1") << endl;
    cout << "vaild_count:" << mmp->vaild_count("queue1") << endl;
    cout << "total_count:" << mmp->total_count("queue1") << endl;
}

int main(int argc, char *argv[])
{
    testing::InitGoogleTest(&argc, argv);
    testing::AddGlobalTestEnvironment(new MessageTest);
    RUN_ALL_TESTS();
    return 0;
}